package com.hrms.service;

import com.hrms.entity.Employee;
import com.hrms.repository.EmployeeRepository;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;

@Service
public class EmployeeService {

    @Autowired
    private EmployeeRepository employeeRepository;

    public Page<Employee> getEmployees(int page, int size, String keyword, Long departmentId, Long positionId, String status) {
        Pageable pageable = PageRequest.of(page, size);
        Employee.Status statusEnum = status != null ? Employee.Status.valueOf(status) : null;
        return employeeRepository.findByFilters(keyword, departmentId, positionId, statusEnum, pageable);
    }

    public Employee getEmployeeById(Long id) {
        return employeeRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("员工不存在"));
    }

    public Employee createEmployee(Employee employee) {
        if (employeeRepository.existsByEmployeeNumber(employee.getEmployeeNumber())) {
            throw new RuntimeException("员工编号已存在");
        }
        return employeeRepository.save(employee);
    }

    public Employee updateEmployee(Long id, Employee employeeDetails) {
        Employee employee = getEmployeeById(id);
        
        employee.setName(employeeDetails.getName());
        employee.setGender(employeeDetails.getGender());
        employee.setBirthDate(employeeDetails.getBirthDate());
        employee.setEmail(employeeDetails.getEmail());
        employee.setPhone(employeeDetails.getPhone());
        employee.setAddress(employeeDetails.getAddress());
        employee.setIdCard(employeeDetails.getIdCard());
        employee.setDepartment(employeeDetails.getDepartment());
        employee.setPosition(employeeDetails.getPosition());
        employee.setHireDate(employeeDetails.getHireDate());
        employee.setSalary(employeeDetails.getSalary());
        employee.setStatus(employeeDetails.getStatus());
        
        return employeeRepository.save(employee);
    }

    public void deleteEmployee(Long id) {
        Employee employee = getEmployeeById(id);
        employee.setStatus(Employee.Status.INACTIVE);
        employeeRepository.save(employee);
    }

    public byte[] exportEmployeesToExcel() {
        List<Employee> employees = employeeRepository.findAll();
        
        try (Workbook workbook = new XSSFWorkbook(); 
             ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            
            Sheet sheet = workbook.createSheet("员工信息");
            
            // 创建表头
            Row headerRow = sheet.createRow(0);
            String[] headers = {"员工编号", "姓名", "性别", "出生日期", "邮箱", "电话", "地址", 
                              "部门", "职位", "入职日期", "薪资", "状态"};
            
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
                
                CellStyle style = workbook.createCellStyle();
                Font font = workbook.createFont();
                font.setBold(true);
                style.setFont(font);
                cell.setCellStyle(style);
            }
            
            // 填充数据
            int rowNum = 1;
            for (Employee employee : employees) {
                Row row = sheet.createRow(rowNum++);
                
                row.createCell(0).setCellValue(employee.getEmployeeNumber());
                row.createCell(1).setCellValue(employee.getName());
                row.createCell(2).setCellValue(employee.getGender());
                row.createCell(3).setCellValue(employee.getBirthDate().toString());
                row.createCell(4).setCellValue(employee.getEmail());
                row.createCell(5).setCellValue(employee.getPhone());
                row.createCell(6).setCellValue(employee.getAddress());
                row.createCell(7).setCellValue(employee.getDepartment() != null ? employee.getDepartment().getName() : "");
                row.createCell(8).setCellValue(employee.getPosition() != null ? employee.getPosition().getName() : "");
                row.createCell(9).setCellValue(employee.getHireDate().toString());
                row.createCell(10).setCellValue(employee.getSalary().doubleValue());
                row.createCell(11).setCellValue(employee.getStatus().name());
            }
            
            // 自动调整列宽
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
            }
            
            workbook.write(outputStream);
            return outputStream.toByteArray();
            
        } catch (IOException e) {
            throw new RuntimeException("导出Excel失败", e);
        }
    }
}
